'use strict';

module.exports = (app) => {
  const { STRING, INTEGER, DATE, Op } = app.Sequelize;

  const User = app.model.define(
    'english_user',
    {
      id: {
        type: INTEGER,
        primaryKey: true,
        autoIncrement: true,
      },
      openid: STRING(255),
      nickname: STRING(255),
      avatar_url: STRING(255),
      created_at: DATE,
      updated_at: DATE,
    },
    {
      freezeTableName: true,
    }
  );

  User.associate = function () {
    app.model.User.belongsToMany(app.model.Word, {
      through: app.model.Progress, // 通过 Progress 表建立关联
      foreignKey: 'user_id', // 用户ID外键
      otherKey: 'word_id', // 单词ID外键
      as: 'words', // 别名（可选）
    });
    app.model.User.hasMany(app.model.WordFavorites, {
      foreignKey: 'user_id',
      as: 'favorites',
    });
    app.model.User.belongsToMany(app.model.Role, {
      through: app.model.UserRole,
      foreignKey: 'user_id',
      as: 'roles',
    });
  };

  User.findByLogin = async function(openid) {
    const user = await this.findOne({
      where: { openid },
      attributes: ['id', 'openid', 'nickname', 'avatar_url'], // 明确需要的字段
      include: [{
        model: app.model.Role,
        as: 'roles',
        attributes: ['is_super'],
        through: { attributes: [] } // 忽略中间表字段
      }]
    });
    
    if (!user) return null;
    
    // 安全转换为普通对象
    const result = user.get({ plain: true });
    
    // 如果需要进一步处理
    result.isSuper = result.roles.some(role => role.is_super);
    
    return result;
  };

  User.findById = async function (id) {
    return await this.findOne({
      where: {
        id,
      },
      attributes: {
        // 排除
        exclude: ['password', 'created_at', 'updated_at'],
      },
    });
  };

  return User;
};
